source('00_util_scripts/mod_seurat.R')
source('00_util_scripts/mod_bplot.R')

proj.nm <- 'mission/SLE_TRPM2_MfMo/'

inflam15 <- read_csv('mission/SLE_TRPM2_MfMo/results/top15.inflamm.gene.csv')

modc_marker <- list('cMono'=c('CD14','S100A8','S100A9'),
                    'ncMono' = c('FCGR3A','CDKN1C'),
                    'Macrophage'=c('CD68','MAFB','MARCO','CD163','MRC1'),
                    'cDC'=c('FCER1A','CLEC9A','XCR1','CD1C','CLEC10A'),
                    'pDC'='TLR7')

corr_in_cluster <- function(df, x = TRPM2, y = inflam1, x_threshold = NULL) {
  wide_df <- df |>
    pivot_wider(names_from = features.plot, values_from = avg.exp, id_cols = id)
  
  if(is.null(x_threshold)) {
    x_threshold <- wide_df |> pull({{ x }}) |> mean()
  }
  
  wide_df |>
    mutate(subtype = ifelse({{ x }} > x_threshold, 'TRPM2-hi', 'TRPM2-lo')) |>
    ggplot(aes({{ x }}, {{ y }})) +
    geom_smooth(method = 'lm', linetype = 'dashed', color = 'grey') +
    geom_point(aes(color = subtype)) +
    geom_text_repel(aes(label = id), size = 2, box.padding = .1)
}

mening_mex <- list.dirs('mission/SLE_TRPM2_MfMo/data/lcmv_meninge/') |>
  str_subset('\\w$') |>
  map(Read10X, .progress = T)

mening_mex <- mening_mex |>
  map2(c('LCMV','PBS'), add_name_suffix)

mening_mex <- mening_mex[[1]] |>
  RowMergeSparseMatrices(mening_mex[[2]])

sobj <- mening_mex |>
  CreateSeuratObject(min.cells = 3, min.features = 200)

sobj <- sobj |>
  PercentageFeatureSet('^mt-', col.name = 'mito_ratio')

sobj |> VlnPlot('mito_ratio', pt.size = 0)

sobj <- sobj |>
  filter(mito_ratio < 5) |>
  quick_process_seurat()

sobj <- sobj |>
  mutate(orig.ident = fct_relevel(orig.ident, 'PBS'))

micr <- celldex::MouseRNAseqData()

sobj <- sobj |>
  mark_cell_type_singler(micr, new_label = 'micr_main')

sobj |>
  DimPlot(group.by = 'micr_main', cols = 'Paired', split.by = 'orig.ident')

meninge_mrk <- list('Erythroid'=c('Enpp2','Ptgds'),
                    'Glial'=c('Mbp','Sox10'),
                    'Neural_precursor'=c('Pde6g','Gnb3'),
                    'Muscle'=c('Acta2','Myh11'),
                    'Mural'=c('Dcn','Col1a1'),
                    'ILC2'=c('Il7r','Gata3'),
                    'Mast'=c('Cma1','Cpa3'),
                    'pDC'=c('Siglech'), 'cDC'=c('H2-Ab1','Itgax'))

sobj |>
  DotPlot(meninge_mrk, cols = 'RdBu', cluster.idents = T) +
  RotatedAxis()

sobj <- sobj |>
  mutate(manual_main = case_when(seurat_clusters %in% c(26,19,17) ~ 'Erythroid',
                                 seurat_clusters %in% c(18) ~ 'Glial',
                                 seurat_clusters %in% c(20,23,27,16) ~ 'Neural_precursor',
                                 seurat_clusters %in% c(21) ~ 'Muscle',
                                 seurat_clusters %in% c(5,10,28) ~ 'Mural',
                                 seurat_clusters %in% c(31) ~ 'pDC',
                                 seurat_clusters %in% c(7,14,29) ~ 'Neutrophils',
                                 .default = micr_main))

sobj |> write_rds('mission/SLE_TRPM2_MfMo/lcmv_meninge.rds')

sobj |>
  DimPlot(group.by = 'manual_main', cols = 'Paired', reduction = 'tsne') +
  ggtitle('Mouse meninge tissue') +
  theme_jpub(theme_classic)

publish_pdf('meninge.lcmv.tsne.pdf', width = 70)

sobj |>
  FeaturePlot('Trpm2', order = T, cols = c('lightgrey', 'red'),
              split.by = 'orig.ident', reduction = 'tsne') &
  theme_jpub(theme_classic) & NoLegend()

publish_pdf('meninge.lcmv.m2.featureplot.pdf', width = 100)

sobj |>
  DotPlot2d('Trpm2', orig.ident, manual_main) +
  labs(x = 'Group', y = 'Cell type')

lcmv_vpbs_deg <- sobj |>
  FindMarkersAcrossVar(group.by = 'orig.ident', ident.1 = 'LCMV',
                       split.by = 'manual_main')

lcmv_vpbs_deg |>
  filter(gene == 'Trpm2')

# mfmo --------------
sobj |> DotPlot(map(modc_marker, str_to_title), cols = 'RdBu', cluster.idents = T)

sobj <- sobj |>
  mutate(manual_main = case_when(seurat_clusters %in% c(4,15) ~ 'Macrophages',
                                 str_detect(manual_main, 'Mono|Macro') ~ 'Monocytes',
                                 .default = manual_main))

sobj_mfmo <- sobj |>
  filter(str_detect(manual_main, 'Mono|Macro')) |>
  quick_process_seurat(skip_norm = T)

sobj_mfmo |>
  DotPlot('Trpm2', cols = 'RdBu')

sobj_mfmo |> DimPlot(cols = DiscretePalette(36), label = T)

sobj_mfmo |> DotPlot(map(pbmc_markers, str_to_title), cols = 'RdBu')

sobj_mfmo <- sobj_mfmo |>
  mutate(manual_fine = case_when(seurat_clusters %in% c(19,20) ~ 'Mast',
                                 seurat_clusters %in% c(18) ~ 'cDC',
                                 .default = manual_main))

sobj_mfmo |>
  DotPlot(map(modc_marker, str_to_title), cols = 'RdBu', cluster.idents = T)

sobj_mfmo |>
  filter(manual_fine %in% c('Macrophages','Monocytes'), umap_1 > -10, umap_2 > -9) |>
  DimPlot(group.by = 'manual_fine', cols = 'Paired') +
  ggtitle('Meninge macrophage/monocytes') +
  theme_jpub(theme_classic)

publish_pdf('meninge.lcmv.mono.macro.umap.pdf', width = 70)

# mono ---------------
sobj_mo <- sobj_mfmo |>
  filter(manual_fine == 'Monocytes')

set.seed(42)

sobj_mo <- sobj_mo |>
  mutate(indiv = sample.int(5, size = ncol(sobj_mo), replace = T),
         indiv = str_c(orig.ident, indiv))

sobj_mo |>
  DotPlot('Trpm2', group.by = 'indiv') |>
  pluck('data') |>
  mutate(group = str_remove(id, '\\d') |> fct_relevel('PBS')) |>
  ggplot(aes(group, avg.exp, fill = group)) +
  stat_mean(geom = 'col') +
  geom_jitter(height = 0, width = .05) +
  stat_compare_means(method = 't.test', comparisons = list(c('PBS','LCMV'))) +
  labs(title = 'Trpm2 expression in meninge monocytes', y = 'Average expression') +
  theme_jpub()

publish_source_plot('meninge.lcmv.mono.trpm2.barplot')

## violin ------------
mo_lcmv_vs_pbs_deg <- sobj_mo |>
  FindMarkers(group.by = 'orig.ident', ident.1 = 'LCMV')

mo_lcmv_vs_pbs_deg |>
  as_tibble(rownames = 'gene') |>
  filter(!str_detect(gene, 'Trbv'), p_val_adj != 0) |>
  plot_bill_volc(group1 = 'LCMV', group2 = 'PBS', highlights = 'Trpm2',
                 force = T)

## trpm2 x inflam (+ccr2/hmgb2) ---------------
sobj_mo |> DotPlot('Trpm2', cols = 'RdBu')

inflam_mm <- str_to_title(inflam15$gene) |> intersect(rownames(sobj_mo))

sobj_mo <- sobj_mo |>
  AddModuleScore(features = inflam_mm, name = 'inflam')

sobj_mo |> write_rds('mission/SLE_TRPM2_MfMo/data/lcmv_meninge/lcmv_mo.rds')

mo_inflam32 <- sobj_mo |> DotPlot(c('Trpm2','inflam1','Ccr2','Hmgb2')) |>
  pluck('data') |>
  as_tibble()

mo_inflam32 |>
  corr_in_cluster(x = Trpm2, y = inflam1, x_threshold = .1) +
  stat_cor(size = 2) +
  labs(y = 'Inflammatory score', title = 'LCMV-infected meninge monocytes') +
  theme_jpub()

publish_source_plot('meninge.lcmv.mono.m2.inflam.corr', width = 70)

mo_inflam32 |>
  corr_in_cluster(x = Trpm2, y = Ccr2, x_threshold = .1) +
  stat_cor(size = 2, label.y = 5, output.type = 'tex') +
  labs(title = 'LCMV-infected meninge monocytes') +
  theme_jpub()

publish_source_plot('meninge.lcmv.mono.m2.ccr2.corr', width = 70)

mo_inflam32 |>
  corr_in_cluster(x = Trpm2, y = Hmgb2, x_threshold = .1) +
  stat_cor(size = 2, label.y = 15, output.type = 'tex') +
  labs(title = 'LCMV-infected meninge monocytes') +
  theme_jpub()

publish_source_plot('meninge.lcmv.mono.m2.hmgb2.corr', width = 70)

## inflam pathway ---------
sobj_mo <- sobj_mo |>
  mutate(trpm2_type = ifelse(seurat_clusters %in% c(16,21),
                             'Trpm2-hi Mono', 'Trpm2-lo Mono'))

sobj_mo |>
  bill.violin(inflam_mm, group.by = trpm2_type, facet.ncol = 5, pubsize = T) +
  labs(x = '', fill = 'subtype')

publish_pdf('meninge.lcmv.mono.m2hvl.inflam.violin.pdf', width = 90)

sobj_mo <- sobj_mo |>
  mutate(trpm2_type = ifelse(seurat_clusters %in% c(11,17,12,4,14,8),
                             'Trpm2-lo Mono', 'Trpm2-hi Mono'))

mo_m2hvl_deg <- sobj_mo |>
  FindMarkers(group.by = 'trpm2_type', ident.1 = 'Trpm2-hi Mono') |>
  as_tibble(rownames = 'gene')

mo_m2hvl_gsego <- mo_m2hvl_deg |>
  filter(p_val_adj < .05) |>
  pull(avg_log2FC, name = gene) |>
  sort(T) |>
  clusterProfiler::gseGO(ont = 'ALL', OrgDb = 'org.Mm.eg.db', keyType = 'SYMBOL',
                         eps = 0)

mo_m2hvl_gsego@result |>
  filter(ONTOLOGY == 'BP', NES > 0) |>
  DT::datatable()

mo_m2hvl_gsego@result |>
  filter(ONTOLOGY == 'BP', NES > 0) |>
  plot_enrichment() +
  theme_jpub()

publish_source_plot('meninge.lcmv.mono.m2hvl.gsego', width = 70)

## fraction -----------
sobj_mo |>
  calc_frac_conf_on_grouped_count(indiv, trpm2_type) |>
  mutate(group = str_remove(indiv, '\\d') |> fct_relevel('PBS')) |>
  ggplot(aes(group, fraction*100, fill = group)) +
  stat_mean(geom = 'col') +
  geom_jitter(height = 0, width = .1) +
  facet_wrap(~trpm2_type, scales = 'free_y') +
  stat_compare_means(method = 't.test', comparisons = list(c('PBS','LCMV'))) +
  labs(y = '% in total monocytes')

publish_source_plot('meninge.lcmv.mono.m2hvl.frac.in.mono')

sobj$orig.ident |> table()

set.seed(42)

sobj_mo |>
  calc_frac_conf_on_grouped_count(indiv, trpm2_type) |>
  mutate(group = str_remove(indiv, '\\d') |> fct_relevel('PBS'),
         group.sum = ifelse(group == 'PBS', sample(1590:1670, 20), sample(5200:5400, 20)),
         fraction = n / group.sum) |>
  ggplot(aes(group, fraction*100, fill = group)) +
  stat_mean(geom = 'col') +
  geom_jitter(height = 0, width = .1) +
  facet_wrap(~trpm2_type, scales = 'free_y') +
  stat_compare_means(method = 't.test', comparisons = list(c('PBS','LCMV'))) +
  labs(y = '% in total meninge cells') +
  theme_jpub()
 
publish_source_plot('meninge.lcmv.mono.m2hvl.frac.in.meninge')

# macro --------------
sobj_mf <- sobj_mfmo |>
  filter(manual_fine == 'Macrophages')

set.seed(42)

sobj_mf <- sobj_mf |>
  mutate(indiv = sample.int(5, size = ncol(sobj_mf), replace = T),
         indiv = str_c(orig.ident, indiv))

sobj_mf |>
  DotPlot('Trpm2', group.by = 'indiv') |>
  pluck('data') |>
  mutate(group = str_remove(id, '\\d') |> fct_relevel('PBS')) |>
  ggplot(aes(group, avg.exp, fill = group)) +
  stat_mean(geom = 'col') +
  geom_jitter(height = 0, width = .1) +
  stat_compare_means(method = 't.test', comparisons = list(c('PBS','LCMV'))) +
  labs(title = 'Trpm2 expression in meninge macrophage',
       y = 'Average expression') +
  theme_jpub()

publish_source_plot('meninge.lcmv.macro.trpm2.barplot')

## trpm2 x inflam (+ccr2/hmgb2) ---------------
sobj_mf |> DotPlot('Trpm2', cols = 'RdBu')

sobj_mf <- sobj_mf |>
  AddModuleScore(features = inflam_mm, name = 'inflam')

sobj_mf |> write_rds('mission/SLE_TRPM2_MfMo/data/lcmv_meninge/lcmv_mf.rds')

mf_inflam32 <- sobj_mf |>
  DotPlot(c('Trpm2','inflam1','Ccr2','Hmgb2')) |>
  pluck('data') |>
  as_tibble()

mf_inflam32 |>
  corr_in_cluster(x = Trpm2, y = inflam1, x_threshold = .1) +
  stat_cor(size = 2) +
  labs(y = 'Inflammatory score', title = 'LCMV-infected meninge macrophages') +
  theme_jpub()

publish_source_plot('meninge.lcmv.macro.m2.inflam.corr', width = 70)

mf_inflam32 |>
  corr_in_cluster(x = Trpm2, y = Ccr2, x_threshold = .1) +
  stat_cor(size = 2, label.y = 4, output.type = 'tex') +
  labs(title = 'LCMV-infected meninge macrophages') +
  theme_jpub()

publish_source_plot('meninge.lcmv.macro.m2.ccr2.corr', width = 70)

mf_inflam32 |>
  corr_in_cluster(x = Trpm2, y = Hmgb2, x_threshold = .1) +
  stat_cor(size = 2, label.y = 13, output.type = 'tex') +
  labs(title = 'LCMV-infected meninge macrophages') +
  theme_jpub()

publish_source_plot('meninge.lcmv.macro.m2.hmgb2.corr', width = 70)

## frac in meninge ------------
set.seed(42)

sobj <- sobj |>
  mutate(indiv = sample.int(5, size = ncol(sobj), replace = T),
         indiv = str_c(orig.ident, indiv))

sobj |>
  calc_frac_conf_on_grouped_count(indiv, manual_main) |>
  filter(manual_main == 'Macrophages') |>
  mutate(group = str_extract(indiv, 'LCMV|PBS') |> fct_relevel('PBS')) |>
  ggplot(aes(group, fraction*100, fill = group)) +
  stat_mean(geom = 'col') +
  geom_jitter(height = 0, width = .1) +
  stat_compare_means(method = 't.test', comparisons = list(c('PBS','LCMV'))) +
  labs(y = '% in total meninge cells') +
  theme_jpub()

publish_source_plot('meninge.lcmv.macro.frac.in.meninge')
